/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 12, 2012  11:03:07 AM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.ps.outbound
 * File Name : SyncGoodsReceiptService.java
 * TODO
 */
package sap.business.mm.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.MmGoodsreceiptOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmGoodsreceiptOutbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class SyncGoodsReceiptService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(SyncGoodsReceiptService.class);
	private static MmGoodsreceiptOutbServices mmGoodsreceiptOutbServ = null;
	
	/**
	 *
	 */
	public SyncGoodsReceiptService() {
		// TODO Auto-generated constructor stub
		try {
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, JCoStructure jCoStructure, List<?> value_list) throws Exception {

		try{
			
			//Check Is not isEmpty is exit method.
			if(!jcoTable.isEmpty())
			{
				log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
				return;
			}	
			
			if(!CommonService.IsNull(value_list)){
				jCoStructure.clear();
				log.info("value_list.size : " + value_list.size());			
				log.info("table.getNumRows : " + jcoTable.getNumRows());
				
				//Header
				MmGoodsreceiptOutb model = (MmGoodsreceiptOutb)value_list.get(0);
				jCoStructure.setValue("GRN_NUMBER", model.getPromisGrnNo());
				//jCoStructure.setValue("GP_TYPE", "76");
				jCoStructure.setValue("BKTXT", model.getRemarks());
				jCoStructure.setValue("XBLNR", model.getSupplierDoNo());
				jCoStructure.setValue("BLDAT", model.getSupplierDoDate());
				jCoStructure.setValue("BUDAT", model.getGrnDate());
				jCoStructure.setValue("BWART", model.getStatus());
				
				jcoTable.deleteAllRows();
				for (Object obj : value_list) 
		        {
					model = (MmGoodsreceiptOutb)obj;
					log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " -- Document No : " + model.getPromisGrnNo() +  " -- SAP PO Document No :" + model.getExternalPoNo());
					jcoTable.appendRow();
					jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
					
					jcoTable.setValue("EBELN", model.getExternalPoNo());
					jcoTable.setValue("EBELP", model.getExternalPoLineItem());
					jcoTable.setValue("MATNR", model.getItemCode());
					jcoTable.setValue("WERKS", model.getProjectPlant());
					jcoTable.setValue("MENGE", model.getItemUmQty());
					jcoTable.setValue("ERFME", model.getItemUm());
					jcoTable.setValue("WEMPF", model.getPreparedBy());
					jcoTable.setValue("SGTXT", model.getArticelDescription());								
					jcoTable.setValue("DEL_IND", ""); 			
		        }
			}
					
			super.SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
		
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		
		List<MmGoodsreceiptOutb> lst = new ArrayList<MmGoodsreceiptOutb>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				MmGoodsreceiptOutb model = mmGoodsreceiptOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			mmGoodsreceiptOutbServ.Updated(lst);
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<MmGoodsreceiptOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<MmGoodsreceiptOutb> newlst = new ArrayList<MmGoodsreceiptOutb>();
				for(MmGoodsreceiptOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new MmGoodsreceiptOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	private List<MmGoodsreceiptOutb> Search() throws Exception 
	{
		try{
			
			String company = "SP";
			String project = "SPLVILLE-PRAGSA";
			String promisGrnNo = "76-1206-000003";
			String status = "101";
			String issync = "Y";
			List<MmGoodsreceiptOutb> lst = mmGoodsreceiptOutbServ.findByDocumentNo(company, project, promisGrnNo, status, issync);
			
			if(!CommonService.IsNull(lst))
				log.info(lst.size());
			else
				log.info(" else  ");
			
			return lst;
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	public void SendToSAP(List<MmGoodsreceiptOutb> value_list) throws Exception
	{
		
		try{
			
			if(!CommonService.IsNull(value_list)){
				
				this.sap_bapi = "ZIN_MMPUR_GR";
				this.sap_structure = "GI_HEAD";
				this.sap_table = "GT_ITEM";
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();
				mmGoodsreceiptOutbServ = new MmGoodsreceiptOutbServices(this.emSynchro);

				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
						
				//List<MmGoodsreceiptOutb> value_list = Search();   //mmGoodsreceiptOutbServ.findAllIsSync("N");
				
				SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
			}	
			
		}catch(Exception e){
			UpdateStagingWhenError(value_list, e);
			log.error(e);
			throw e;
		}
			
	}
	
	
	private void Start() throws Exception
	{
		this.sap_bapi = "ZIN_MMPUR_GR";
		this.sap_structure = "GI_HEAD";
		this.sap_table = "GT_ITEM";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();
		mmGoodsreceiptOutbServ = new MmGoodsreceiptOutbServices(this.emSynchro);
		
		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
				
		List<MmGoodsreceiptOutb> value_list = Search();   //mmGoodsreceiptOutbServ.findAllIsSync("N");
		
		SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}
	
//	public static void main(String [] agrs){		
//		
//		try {
//			
//			SyncGoodsReceiptService xx = new SyncGoodsReceiptService();
//			
//			xx.Start();
//			
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			log.error(e);
//			e.printStackTrace();
//		}
//		
//	}
	
}
